<template>
  <div>
    <el-dialog title="修改角色" :visible="dialogVisible" width="80%" @close="close">
      <el-form>
        <el-row>
          <el-col :sm="24">
            <el-form-item label>
              <el-checkbox-group v-model="roles">
                <el-checkbox
                  v-for="role in allroles"
                  :label="role.id"
                  :key="role.id"
                >{{role.name}}</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer" style="text-align: left;">
        <el-button type="primary" @click="editAdmin">保存数据</el-button>
        <el-button @click="close">关闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { roleSelectJson } from "@/api/role";
import { editAdmin } from "@/api/admin";
export default {
  props: {
    dialogVisible: {
      type: Boolean,
      default: false
    },
    originData: {
      type: Object,
      default() {
        return null;
      }
    }
  },
  watch: {
    originData() {
      if (this.originData) {
        this.roles = this.originData.roleids.split(",").map(e => {
          return Number.parseInt(e);
        });
        for (let key in this.originData) {
          this.formData[key] = this.originData[key];
        }
      }
    }
  },
  data() {
    return {
      roles: [],
      allroles: [],
      formData: {}
    };
  },
  created() {
    this.fetchRoleList();
  },
  methods: {
    close() {
      this.$emit("update:dialogVisible", false);
    },
    //获取用户角色信息
    async fetchRoleList() {
      var params = { type: 1 };
      let allroles = await roleSelectJson(params);
      console.log(this.allroles);
      this.allroles.push(...allroles);
    },
    async editAdmin() {
      this.formData.rolestr = this.roles.filter(e => e).join(",");
      let r = await editAdmin(this.formData);
      if (r && r.error == 0) {
        this.$message({
          message: "操作成功",
          type: "success"
        });
        this.$emit("update:dialogVisible", false);
      } else {
        this.$message({
          message: "操作失败",
          type: "error"
        });
      }
    }
  }
};
</script>